var flotOptions = {
      legend:{noColumns:5,container:"#flotlegendholder"},grid:{hoverable:true},
      xaxis:{mode:"time",ticks:5},yaxes:[{},{min:0,max:1.05,show:false}]
    },
    flotDatasetOptions = {lines:{ show:true},clickable:false,hoverable:false},
    flotDatasetOptionsText = {points:{ show:true},yaxis:2,clickable:false,hoverable:true};
var p; //plotobject
function getEntry(){
  var pp,i,p,params = {};
  p = location.search.substr(1).split("&");
  for(i = 0; i < p.length; i++){
    pp = p[i].split("=");
    params[pp[0]] = pp[1];
  }
  return params.entry + ":" + params.directory;;
}
function checkEntry(entry,callback){
  chrome.fileSystem.isRestorable(entry, function(bIsRestorable){
    chrome.fileSystem.restoreEntry(entry, function(theEntry) { 
      if(theEntry){ callback(theEntry);}
      else{console.log("Project not found");}
    });
  });
}
function getSubTree(entry,name,callback){
  var dirReader = entry.createReader();
  dirReader.readEntries (function(results) {
    for(var i = 0; i < results.length; i++){
      if(results[i].name === name){
        callback(results[i]);
        return;
      }
    }
    callback(false);
  });
}
function showLogTable(dirEntry,callback){
  var dirReader = dirEntry.createReader();
  dirReader.readEntries(function(results){
    var html = '<select id="logTable">';
    for(var i = 0; i < results.length; i++){
      html += '<option value="' + chrome.fileSystem.retainEntry(results[i]) + '">' + results[i].name + '\n';  
    }
    html += '</select>';
    callback(html);
  });
}
function loadList(){
  var entry = $("#logTable").val();
  chrome.fileSystem.restoreEntry(entry, function(theEntry) { 
    if(theEntry){
      var reader = new FileReader();
      reader.onload = function(e){ showChart(e.target.result);};
      theEntry.file(function(file){ reader.readAsText(file);});
    }
    else{console.log("File not found");}
  });
}
function showChart(data){
  var dt,dp,i,j,logData,flotTemp,flotData;
  dt = JSON.parse(data);
  logData = dt[0];
  dt.shift();
  flotTemp = {};
  for(i = 0; i < logData.dataPoints.length; i++){
    dp = logData.dataPoints[i];
    flotTemp[dp.label] = {data:[],label:dp.label,type:dp.type,lastValue:""};
    switch(dp.type){
      case "number":$.extend(flotTemp[dp.label],flotDatasetOptions);break;
      case "string":$.extend(flotTemp[dp.label],flotDatasetOptionsText);break;
    } 
  }
  for(i = 0; i < dt.length; i++){
    for(j in dt[i].data){
      switch(flotTemp[j].type){
        case "number":flotTemp[j].data.push([dt[i].UTC,dt[i].data[j]]);break;
        case "string":
          if(dt[i].data[j] !== flotTemp[j].lastValue){
            flotTemp[j].lastValue = dt[i].data[j];
            flotTemp[j].data.push([dt[i].UTC,1,dt[i].data[j]]);
          }
          break;
      }
    }  
  }
  flotData = [];
  for(i = 0; i < logData.dataPoints.length; i++){flotData.push(flotTemp[logData.dataPoints[i].label]);}
  p = $.plot($("#placeholder"),flotData,flotOptions);
console.log(p.getData());
  $("#placeholder").unbind().on("plothover",function(event,pos,item){
    if(item){
      $("#flottooltip").html("changed to " + item.series.data[item.dataIndex][2])
        .css({top: item.pageY+5, left: item.pageX+5}).show();
    }
    else {$("#flottooltip").hide();}
  });
  $.plot($("#overview"),flotData,$.extend(flotOptions,
    {legend:{show:false},selection:{mode:"xy"},grid:{hoverable:false} } ));
  $("#overview").bind("plotselected",function (event, ranges) {p.setSelection(ranges);});
  $("#placeholder").bind("plotselected",function (event, ranges) {
    if (ranges.xaxis.to - ranges.xaxis.from < 0.00001) { ranges.xaxis.to = ranges.xaxis.from + 0.00001;}
    if (ranges.yaxis.to - ranges.yaxis.from < 0.00001) { ranges.yaxis.to = ranges.yaxis.from + 0.00001;}
    $.plot("#placeholder", flotData,
      $.extend(true, {}, flotOptions, {
        xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
        yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
      })
    );
  });
}

$(document).ready(function(){
  $("<div id='flottooltip'></div>").css({
    position: "absolute",display: "none",border: "1px solid #fdd",
    padding: "2px","background-color": "#fee",opacity: 0.80
  }).appendTo("body");
  checkEntry(getEntry(),function(theEntry){
    getSubTree(theEntry,"testinglog",function(subDirEntry){
      showLogTable(subDirEntry,function(html){
        $("#logList").html(html);
        $("#loadList").unbind().click(loadList);    
      });
    });
  });
});
